package com.wyl.springboot;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

	private final static Logger logger = LoggerFactory.getLogger(MainApp.class);
	
	private final static String serverName = "springstudy";
	
	private static volatile boolean running = true;
	
	public static void main(String[] args) {
		try {
			logger.info("{} server is starting …… ", serverName);
			final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
			context.start();
			logger.info("{} server is started successful.", serverName);
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					context.close();
					logger.info("{} server has stoped !", serverName);
					synchronized (MainApp.class) {
						running = false;
						MainApp.class.notifyAll();
					}
				}
			});
		} catch (RuntimeException re) {
			String errorMsg = MessageFormat.format("{0} server start with Exception ! ", serverName);
			logger.error(errorMsg, re);
			System.exit(1);
		}
		synchronized (MainApp.class) {
			while(running) {
				try {
					MainApp.class.wait();
				} catch (InterruptedException ie) {
					String errorMsg = MessageFormat.format("{0} server main thread waiting Exception ! ", serverName);
					logger.error(errorMsg, ie);
				}
			}
		}
	}

}
